package com.grm.table.driven;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

/**
 * 演示优化大量if-else(表驱动法)
 *
 * @author gaorimao
 * @since 2022/02/22
 */
public class TableDriven {
    private static Map<String, Function<String, Integer>> map = new HashMap<>();

    static {
        map.put("aaa", TableDriven::doAction1);
        map.put("bbb", TableDriven::doAction2);
        map.put("ccc", TableDriven::doAction3);
        map.put("ddd", TableDriven::doAction4);
        map.put("eee", TableDriven::doAction5);
        map.put("fff", TableDriven::doAction6);
    }


    public static void main(String[] args) {
        chooseAction("aaa");
        chooseAction("bbb");
        chooseAction("ccc");
        chooseAction("ddd");
        chooseAction("eee");
        chooseAction("fff");
    }

    private static void chooseAction(String str) {
        for (Map.Entry<String, Function<String, Integer>> entry : map.entrySet()) {
            String key = entry.getKey();
            if (str.contains(key)) {
                entry.getValue().apply(str);
            }
        }
    }

    private static Integer doAction1(String params) {
        System.out.println("doAction1");
        return 0;
    }

    private static Integer doAction2(String params) {
        System.out.println("doAction2");
        return 0;
    }

    private static Integer doAction3(String params) {
        System.out.println("doAction3");
        return 0;
    }

    private static Integer doAction4(String params) {
        System.out.println("doAction4");
        return 0;
    }

    private static Integer doAction5(String params) {
        System.out.println("doAction5");
        return 0;
    }

    private static Integer doAction6(String params) {
        System.out.println("doAction6");
        return 0;
    }
}
